/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.shardingsphere.test.natived.commons.repository;

import org.apache.shardingsphere.test.natived.commons.entity.OrderItem;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

@SuppressWarnings({"SqlDialectInspection", "SqlNoDataSourceInspection"})
public final class OrderItemRepository {
    
    private final DataSource dataSource;
    
    public OrderItemRepository(final DataSource dataSource) {
        this.dataSource = dataSource;
    }
    
    /**
     * create table if not exists in MySQL.
     *
     * @throws SQLException SQL exception
     */
    public void createTableIfNotExistsInMySQL() throws SQLException {
        String sql = "CREATE TABLE IF NOT EXISTS t_order_item"
                + "(order_item_id BIGINT NOT NULL AUTO_INCREMENT,order_id BIGINT NOT NULL,user_id INT NOT NULL,phone VARCHAR(50),status VARCHAR(50),PRIMARY KEY (order_item_id))";
        try (
                Connection connection = dataSource.getConnection();
                Statement statement = connection.createStatement()) {
            statement.executeUpdate(sql);
        }
    }
    
    /**
     * create table if not exists in Postgres.
     *
     * @throws SQLException SQL exception
     */
    public void createTableIfNotExistsInPostgres() throws SQLException {
        String sql = "CREATE TABLE IF NOT EXISTS t_order_item (order_item_id BIGSERIAL PRIMARY KEY,order_id BIGINT NOT NULL,user_id INTEGER NOT NULL,phone VARCHAR(50),status VARCHAR(50))";
        try (
                Connection connection = dataSource.getConnection();
                Statement statement = connection.createStatement()) {
            statement.executeUpdate(sql);
        }
    }
    
    /**
     * create table in MS SQL Server. `order_item_id` is not set to `IDENTITY(1,1)` to simplify the unit test.
     * This also ignored the default schema of the `dbo`.
     *
     * @throws SQLException SQL exception
     */
    public void createTableInSQLServer() throws SQLException {
        String sql = "CREATE TABLE [t_order_item] (order_item_id bigint NOT NULL,order_id bigint NOT NULL,user_id int NOT NULL,phone varchar(50),status varchar(50),PRIMARY KEY (order_item_id))";
        try (
                Connection connection = dataSource.getConnection();
                Statement statement = connection.createStatement()) {
            statement.executeUpdate(sql);
        }
    }
    
    /**
     * create table in Firebird.
     * Cannot use `create table if not exists` for Docker Image `firebirdsql/firebird`,
     * see <a href="https://github.com/FirebirdSQL/firebird/issues/8062">FirebirdSQL/firebird#8062</a>.
     *
     * @throws SQLException SQL exception
     */
    public void createTableInFirebird() throws SQLException {
        String sql = "CREATE TABLE t_order_item"
                + "(order_item_id BIGINT generated by default as identity PRIMARY KEY,order_id BIGINT NOT NULL,user_id INT NOT NULL,phone VARCHAR(50),status VARCHAR(50))";
        try (
                Connection connection = dataSource.getConnection();
                Statement statement = connection.createStatement()) {
            statement.executeUpdate(sql);
        }
    }
    
    /**
     * create ACID table in HiveServer2.
     * Hive does not support `AUTO_INCREMENT`,
     * refer to <a href="https://issues.apache.org/jira/browse/HIVE-6905">HIVE-6905</a>.
     *
     * @throws SQLException SQL exception
     */
    public void createAcidTableInHiveServer2() throws SQLException {
        String sql = "CREATE TABLE IF NOT EXISTS t_order_item (order_item_id BIGINT NOT NULL,order_id BIGINT NOT NULL,user_id INT NOT NULL,phone VARCHAR(50),status VARCHAR(50),"
                + "PRIMARY KEY (order_item_id) disable novalidate) CLUSTERED BY (order_item_id) INTO 2 BUCKETS STORED AS ORC TBLPROPERTIES ('transactional' = 'true')";
        try (
                Connection connection = dataSource.getConnection();
                Statement statement = connection.createStatement()) {
            statement.executeUpdate(sql);
        }
    }
    
    /**
     * drop table in MySQL.
     *
     * @throws SQLException SQL exception
     */
    public void dropTableInMySQL() throws SQLException {
        String sql = "DROP TABLE IF EXISTS t_order_item";
        try (
                Connection connection = dataSource.getConnection();
                Statement statement = connection.createStatement()) {
            statement.executeUpdate(sql);
        }
    }
    
    /**
     * drop table in Firebird.
     * Docker Image `firebirdsql/firebird` does not work with `DROP TABLE IF EXISTS`.
     * See <a href="https://github.com/FirebirdSQL/firebird/issues/4203">FirebirdSQL/firebird#4203</a> .
     *
     * @throws SQLException SQL exception
     */
    public void dropTableInFirebird() throws SQLException {
        String sql = "DROP TABLE t_order_item";
        try (
                Connection connection = dataSource.getConnection();
                Statement statement = connection.createStatement()) {
            statement.executeUpdate(sql);
        }
    }
    
    /**
     * truncate table.
     *
     * @throws SQLException SQL exception
     */
    public void truncateTable() throws SQLException {
        String sql = "TRUNCATE TABLE t_order_item";
        try (
                Connection connection = dataSource.getConnection();
                Statement statement = connection.createStatement()) {
            statement.executeUpdate(sql);
        }
    }
    
    /**
     * create shadow table if not exists.
     *
     * @throws SQLException SQL exception
     */
    public void createTableIfNotExistsShadow() throws SQLException {
        String sql = "CREATE TABLE IF NOT EXISTS t_order_item "
                + "(order_item_id BIGINT NOT NULL AUTO_INCREMENT, order_id BIGINT NOT NULL, user_id INT NOT NULL, phone "
                + "VARCHAR(50), status VARCHAR(50), PRIMARY KEY (order_item_id)) /* SHARDINGSPHERE_HINT:shadow=true,foo=bar*/";
        try (
                Connection connection = dataSource.getConnection();
                Statement statement = connection.createStatement()) {
            statement.executeUpdate(sql);
        }
    }
    
    /**
     * drop shadow table.
     *
     * @throws SQLException SQL exception
     */
    public void dropTableShadow() throws SQLException {
        String sql = "DROP TABLE t_order_item /* SHARDINGSPHERE_HINT:shadow=true,foo=bar*/";
        try (
                Connection connection = dataSource.getConnection();
                Statement statement = connection.createStatement()) {
            statement.executeUpdate(sql);
        }
    }
    
    /**
     * truncate shadow table.
     *
     * @throws SQLException SQL exception
     */
    public void truncateTableShadow() throws SQLException {
        String sql = "TRUNCATE TABLE t_order_item /* SHARDINGSPHERE_HINT:shadow=true,foo=bar*/";
        try (
                Connection connection = dataSource.getConnection();
                Statement statement = connection.createStatement()) {
            statement.executeUpdate(sql);
        }
    }
    
    /**
     * insert OrderItem to table.
     *
     * @param orderItem orderItem
     * @return orderItemId of the insert statement
     * @throws SQLException SQL Exception
     */
    public Long insert(final OrderItem orderItem) throws SQLException {
        return insert(orderItem, Statement.RETURN_GENERATED_KEYS);
    }
    
    /**
     * insert OrderItem to table. Databases like ClickHouse do not support returning auto generated keys after executing SQL,
     * see <a href="https://github.com/ClickHouse/ClickHouse/issues/56228">ClickHouse/ClickHouse#56228</a> .
     *
     * @param orderItem         orderItem
     * @param autoGeneratedKeys a flag indicating whether auto-generated keys should be returned; one of {@code Statement.RETURN_GENERATED_KEYS} or {@code Statement.NO_GENERATED_KEYS}
     * @return orderItemId of the insert statement
     * @throws SQLException SQL exception
     */
    @SuppressWarnings("MagicConstant")
    public Long insert(final OrderItem orderItem, final int autoGeneratedKeys) throws SQLException {
        String sql = "INSERT INTO t_order_item (order_id, user_id, phone, status) VALUES (?, ?, ?, ?)";
        try (
                Connection connection = dataSource.getConnection();
                PreparedStatement preparedStatement = connection.prepareStatement(sql, autoGeneratedKeys)) {
            preparedStatement.setLong(1, orderItem.getOrderId());
            preparedStatement.setInt(2, orderItem.getUserId());
            preparedStatement.setString(3, orderItem.getPhone());
            preparedStatement.setString(4, orderItem.getStatus());
            preparedStatement.executeUpdate();
            try (ResultSet resultSet = preparedStatement.getGeneratedKeys()) {
                if (resultSet.next()) {
                    orderItem.setOrderItemId(resultSet.getLong(1));
                }
            }
        }
        return orderItem.getOrderItemId();
    }
    
    /**
     * delete by orderItemId.
     *
     * @param orderItemId order item ID
     * @throws SQLException SQL exception
     */
    public void delete(final Long orderItemId) throws SQLException {
        String sql = "DELETE FROM t_order_item WHERE order_id=?";
        try (
                Connection connection = dataSource.getConnection();
                PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            preparedStatement.setLong(1, orderItemId);
            preparedStatement.executeUpdate();
        }
    }
    
    /**
     * delete by orderItemId in ClickHouse.
     *
     * @param orderItemId orderItemId
     * @throws SQLException SQL exception
     */
    public void deleteInClickHouse(final Long orderItemId) throws SQLException {
        String sql = "ALTER TABLE t_order_item delete WHERE order_id=?";
        try (
                Connection connection = dataSource.getConnection();
                PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            preparedStatement.setLong(1, orderItemId);
            preparedStatement.executeUpdate();
        }
    }
    
    /**
     * select all.
     *
     * @return order items
     * @throws SQLException SQL exception
     */
    public List<OrderItem> selectAll() throws SQLException {
        String sql = "SELECT i.* FROM t_order o, t_order_item i WHERE o.order_id = i.order_id";
        List<OrderItem> result = new LinkedList<>();
        try (
                Connection connection = dataSource.getConnection();
                PreparedStatement preparedStatement = connection.prepareStatement(sql);
                ResultSet resultSet = preparedStatement.executeQuery()) {
            while (resultSet.next()) {
                OrderItem orderItem = new OrderItem();
                orderItem.setOrderItemId(resultSet.getLong(1));
                orderItem.setOrderId(resultSet.getLong(2));
                orderItem.setUserId(resultSet.getInt(3));
                orderItem.setPhone(resultSet.getString(4));
                orderItem.setStatus(resultSet.getString(5));
                result.add(orderItem);
            }
        }
        return result;
    }
    
    /**
     * Assert rollback with transactions.
     * This is currently just a simple test against a non-existent table {@code t_order_item_does_not_exist}
     * and does not involve the competition scenario of distributed transactions.
     *
     * @throws SQLException An exception that provides information on a database access error or other errors.
     */
    public void assertRollbackWithTransactions() throws SQLException {
        try (Connection conn = dataSource.getConnection()) {
            try {
                conn.setAutoCommit(false);
                conn.createStatement().executeUpdate("INSERT INTO t_order_item (order_id, user_id, phone, status) VALUES (2024, 2024, '13800000001', 'INSERT_TEST')");
                conn.createStatement().executeUpdate("INSERT INTO t_order_item_does_not_exist (test_id_does_not_exist) VALUES (2024)");
                conn.commit();
            } catch (final SQLException ignored) {
                conn.rollback();
            } finally {
                conn.setAutoCommit(true);
            }
        }
        try (Connection conn = dataSource.getConnection()) {
            ResultSet resultSet = conn.createStatement().executeQuery("SELECT * FROM t_order_item WHERE user_id = 2024");
            assertThat(resultSet.next(), is(false));
        }
        try (Connection conn = dataSource.getConnection()) {
            try {
                conn.setAutoCommit(false);
                conn.createStatement().executeUpdate("INSERT INTO t_order_item (order_id, user_id, phone, status) VALUES (2025, 2025, '13800000001', 'INSERT_TEST')");
                conn.commit();
            } catch (final SQLException ignored) {
                conn.rollback();
            } finally {
                conn.setAutoCommit(true);
            }
        }
        try (Connection conn = dataSource.getConnection()) {
            ResultSet resultSet = conn.createStatement().executeQuery("SELECT * FROM t_order_item WHERE user_id = 2025");
            assertThat(resultSet.next(), is(true));
        }
    }
}
